package com.xdf.whiteaccount.utils;

import com.xdf.whiteaccount.dto.ExcelInputParamDTO;
import com.xdf.whiteaccount.dto.ExcelOutputParamDTO;
import com.xdf.whiteaccount.dto.ExcelSheet;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: xzy-management-system
 * @description: Excel操作工具
 * @author: 张柯
 * @create: 2021-01-05 17:29
 **/
@Slf4j
@Component
public class ExcelUtil {
    private static final String SET = "set";
    private static final String GET = "get";

    /**
     * 将Excel文件转化
     *
     * @param inputStream 输入流
     * @param param       参数
     * @param clazz       class
     * @param <T>
     * @return
     */
    public <T> List<T> readExcel(InputStream inputStream, ExcelInputParamDTO param, Class<T> clazz) {
        List<T> list = new ArrayList<>();
        FormulaEvaluator formulaEvaluator = null;
        if (inputStream == null) {
            log.debug("读取文件为空！");
            return list;
        }
        boolean isXls = false;
        String fileName = param.getFileName();
        if (StringUtils.isEmpty(fileName) || !fileName.contains(".xlsx")) {
            isXls = true;
        }
        try (Workbook workbook = getWorkBook(inputStream, isXls)) {
            if (formulaEvaluator == null) {
                if (isXls) {
                    formulaEvaluator = new HSSFFormulaEvaluator((HSSFWorkbook) workbook);
                } else {
                    formulaEvaluator = new XSSFFormulaEvaluator((XSSFWorkbook) workbook);
                }
            }
            Map<String, Integer> fields = param.getFieldSetting();
            int sheetCount = workbook.getNumberOfSheets();
            if (sheetCount <= 0) return list;
            if (param.getSheetIndex() == null) {
                param.setSheetIndex(0);
            }
            if (param.getSheetIndex() > sheetCount - 1) {
                param.setSheetIndex(sheetCount - 1);
            }
            Sheet sheet = workbook.getSheetAt(param.getSheetIndex());
            int countOfRows = sheet.getPhysicalNumberOfRows();
            if (param.getTo() != null) countOfRows = param.getTo();
            for (int numberOfRow = param.getFrom(); numberOfRow < countOfRows; numberOfRow++) {
                Row row = sheet.getRow(numberOfRow);
                T object = clazz.newInstance();
                for (Field field : clazz.getDeclaredFields()) {
                    if (Modifier.isStatic(field.getModifiers())) continue;
                    field.setAccessible(true);
                    Method method = clazz.getMethod(findSetterMethod(field), field.getType());
                    String fieldName = field.getName();
                    Class<?> type = field.getType();
                    Integer cellIndex = fields.get(fieldName);
                    if (cellIndex == null) {
                        log.info(fieldName + "字段没有设置");
                        continue;
                    }
                    Cell cell = row.getCell(cellIndex);
                    Object var1;
                    try {
                        var1 = getCellValue(cell, formulaEvaluator, type);
                    } catch (Exception e) {
                        var1 = null;
                    }
                    if (var1 != null && String.valueOf(var1).toUpperCase().equals("NULL")) {
                        var1 = null;
                    }
                    method.invoke(object, var1);
                }
                list.add(object);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return null;
    }

    /**
     * @param inputStream
     * @param param
     * @return
     */
    public List<Map<String, Object>> readExcel(InputStream inputStream, ExcelInputParamDTO param, List<com.xdf.whiteaccount.utils.Field> fieldList) {
        List<Map<String, Object>> list = new ArrayList<>();
        FormulaEvaluator formulaEvaluator = null;
        if (inputStream == null) {
            log.debug("读取文件为空！");
            return list;
        }
        boolean isXls = false;
        String fileName = param.getFileName();
        if (StringUtils.isEmpty(fileName) || !fileName.contains(".xlsx")) {
            isXls = true;
        }
        try (Workbook workbook = getWorkBook(inputStream, isXls)) {
            if (formulaEvaluator == null) {
                if (isXls) {
                    formulaEvaluator = new HSSFFormulaEvaluator((HSSFWorkbook) workbook);
                } else {
                    formulaEvaluator = new XSSFFormulaEvaluator((XSSFWorkbook) workbook);
                }
            }
            int sheetCount = workbook.getNumberOfSheets();
            if (sheetCount <= 0) return list;
            if (param.getSheetIndex() == null) {
                param.setSheetIndex(0);
            }
            if (param.getSheetIndex() > sheetCount - 1) {
                param.setSheetIndex(sheetCount - 1);
            }
            Sheet sheet = workbook.getSheetAt(param.getSheetIndex());
            int countOfRows = sheet.getPhysicalNumberOfRows();
            if (param.getTo() != null) countOfRows = param.getTo();
            for (int numberOfRow = param.getFrom(); numberOfRow < countOfRows; numberOfRow++) {
                Row row = sheet.getRow(numberOfRow);
                Map<String, Object> map = new HashMap<>();

                for (com.xdf.whiteaccount.utils.Field field : fieldList) {
                    Cell cell = row.getCell(field.getSerialNo());
                    Object var1;
                    try {
                        var1 = getCellValue(cell, formulaEvaluator, field.getFieldType());
                    } catch (Exception e) {
                        var1 = null;
                    }
                    if (var1 != null && String.valueOf(var1).toUpperCase().replace(" ", "").equals("NULL")) {
                        var1 = null;
                    }
                    map.put(field.getFieldName(), var1);
                }
                list.add(map);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return null;
    }

    /**
     * Excel写入
     *
     * @param outputStream
     * @param param
     * @return
     */
    public boolean writeExcel(OutputStream outputStream, ExcelOutputParamDTO param) {
        try (SXSSFWorkbook workbook = new SXSSFWorkbook()) {
            List<ExcelSheet> sheets = param.getDataSource();
            if (sheets == null || sheets.size() <= 0) return false;
            for (ExcelSheet sheet : sheets) {
                int currentRowIndex = 0;
                int maxRowLength = 0;
                boolean hasTopic = false;
                List<Map<Integer, Object>> list = sheet.getData();
                SXSSFSheet sxssfSheet = workbook.createSheet(sheet.getSheetName());
                CellStyle cellStyle = workbook.createCellStyle();
                cellStyle.setAlignment(HorizontalAlignment.CENTER);
                cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
                if (StringUtils.isNotEmpty(sheet.getTopic())) {
                    hasTopic = true;
                    SXSSFRow row = sxssfSheet.createRow(currentRowIndex++);
                    SXSSFCell cell = row.createCell(0);
                    cell.setCellValue(sheet.getTopic());
                    cell.setCellStyle(cellStyle);
                }
                if (sheet.getColumns() != null && sheet.getColumns().size() > 0) {
                    SXSSFRow row = sxssfSheet.createRow(currentRowIndex++);
                    for (Integer index : sheet.getColumns().keySet()) {
                        if (index > maxRowLength) {
                            maxRowLength = index;
                        }
                        SXSSFCell cell = row.createCell(index);
                        Object item = sheet.getColumns().get(index);
                        setCellValue(cell, item);
                        cell.setCellStyle(cellStyle);
                    }
                }
                for (Map<Integer, Object> integerObjectMap : list) {
                    SXSSFRow row = sxssfSheet.createRow(currentRowIndex++);
                    Map<Integer, Object> map = integerObjectMap;
                    for (Integer index : map.keySet()) {
                        if (index > maxRowLength) {
                            maxRowLength = index;
                        }
                        SXSSFCell cell = row.createCell(index);
                        cell.setCellValue(String.valueOf(map.get(index)));
                    }
                }
                if (maxRowLength > 0 && hasTopic) {
                    sxssfSheet.addMergedRegion(new CellRangeAddress(0, 0, 0, maxRowLength));
                }
            }
            workbook.write(outputStream);
            return true;
        } catch (IOException e) {
            //  异常处理
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return false;
    }

    /**
     * 获取Workbook对象
     *
     * @return
     */
    public static Workbook getWorkBook(InputStream inputStream, boolean isXls) {
        Workbook workbook = null;
        try {
            workbook = WorkbookFactory.create(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return workbook;
    }

    /**
     * 转换类型
     *
     * @param clazz
     * @param value
     * @return
     */
    public static Object conventType(Class<?> clazz, String value) {
        if (StringUtils.isEmpty(value)) return null;
        if (Integer.class == clazz || int.class == clazz) {
            if (value.contains(".")) value = value.substring(0, value.indexOf('.'));
            return Integer.parseInt(value);
        } else if (Double.class == clazz || double.class == clazz) {
            return Double.parseDouble(value);
        } else if (Long.class == clazz || long.class == clazz) {
            if (value.contains(".")) value = value.substring(0, value.indexOf('.'));
            return Long.parseLong(value);
        } else if (Short.class == clazz || short.class == clazz) {
            return Short.parseShort(value);
        } else if (Boolean.class == clazz || boolean.class == clazz) {
            return Boolean.parseBoolean(value);
        } else if (Byte.class == clazz || byte.class == clazz) {
            return Byte.parseByte(value);
        } else if (Float.class == clazz || float.class == clazz) {
            return Float.parseFloat(value);
        } else if (BigDecimal.class == clazz) {
            return new BigDecimal(value);
        } else {
            return value;
        }
    }

    /**
     * 获取单元格数据
     *
     * @param cell
     * @return
     */
    private static Object getCellValue(Cell cell) {
        if (cell == null) return null;
        CellType cellType = cell.getCellType();
        if (cellType == null) return null;
        switch (cellType) {
            case STRING:
                return cell.getRichStringCellValue().getString();
            case NUMERIC:
                return cell.getNumericCellValue();
            case BOOLEAN:
                return cell.getBooleanCellValue();
            case ERROR:
            case BLANK:
            case _NONE:
                return null;
            default:
                return cell.getStringCellValue();
        }
    }

    /**
     * 获取单元格值
     *
     * @param cell
     * @param formulaEvaluator
     * @param clazz
     * @return
     */
    public static Object getCellValue(Cell cell, FormulaEvaluator formulaEvaluator, Class<?> clazz) {
        CellType cellType = cell.getCellType();
        if (CellType.FORMULA.equals(cellType)) {
            String var = formulaEvaluator.evaluate(cell).formatAsString();
            return conventType(clazz, var);
        }
        return conventType(clazz, String.valueOf(getCellValue(cell)));
    }

    /**
     * 设置
     *
     * @param cell
     * @param value
     */
    private static void setCellValue(Cell cell, Object value) {
        if (value == null) {
            cell.setBlank();
        } else if (value instanceof Integer) {
            cell.setCellValue((int) value);
        } else if (value instanceof Double) {
            cell.setCellValue((double) value);
        } else if (value instanceof Boolean) {
            cell.setCellValue(Boolean.parseBoolean(String.valueOf(value)));
        } else {
            cell.setCellValue(String.valueOf(value));
        }
    }

    /**
     * 获取Set方法
     *
     * @param field
     * @return
     */
    public static String findSetterMethod(Field field) {
        return SET + StringUtil.capitalize(field.getName());
    }

    /**
     * 获取Get方法
     *
     * @param field
     * @return
     */
    public static String findGetterMethod(Field field) {
        return GET + StringUtil.capitalize(field.getName());
    }

}
